import 'dart:async';

import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:jet_rails/jr_app/jr_views/jr_login/jr_login_view.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_blur_container.dart';
import 'package:jet_rails/jr_constant/jr_keys.dart';
import 'package:jet_rails/jr_utils/jr_shared_preferences.dart';

class JrSplashView extends StatefulWidget {
  const JrSplashView({super.key});

  @override
  State<JrSplashView> createState() => JrSplashViewState();
}

class JrSplashViewState extends State<JrSplashView> {
  static const int splashCount = 3;
  SwiperController? swiperController;
  int index = 0;

  Timer? autoGoNextTimer;

  @override
  void initState() {
    super.initState();
    JrSP.instance.setBool(JrKeys.kShowSplash, false);
    swiperController ??= SwiperController()
      ..addListener(() {
        refreshTimer();
      });
    refreshTimer();
  }

  bool get isLast => index == splashCount - 1;

  void refreshTimer() {
    autoGoNextTimer?.cancel();
    autoGoNextTimer = Timer(const Duration(seconds: 2), goNextOrLogin);
  }

  @override
  void dispose() {
    autoGoNextTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(children: [
        Swiper(
          loop: false,
          itemCount: splashCount,
          controller: swiperController,
          physics: const ClampingScrollPhysics(),
          itemBuilder: (BuildContext context, int index) {
            return getSplashPage('assets/images/splash_${index + 1}.png', isLast: index == splashCount - 1);
          },
          onIndexChanged: (value) => setState(() {
            index = value;
          }),
        ),
        buildBtn()
      ]),
    );
  }

  Widget getSplashPage(String assetsImageName, {bool isLast = false}) {
    Widget page = Stack(
      children: [
        Positioned(top: 0, left: 0, right: 0, bottom: 0, child: Image.asset(assetsImageName, fit: BoxFit.fill)),
      ],
    );
    if (isLast) {
      double startX = 0;
      double endX = 0;
      page = GestureDetector(
        behavior: HitTestBehavior.translucent,
        onHorizontalDragStart: (DragStartDetails d) => startX = d.globalPosition.dx,
        onHorizontalDragUpdate: (DragUpdateDetails d) => endX = d.globalPosition.dx,
        onHorizontalDragEnd: (DragEndDetails d) {
          if (endX - startX < -80.0 || d.velocity.pixelsPerSecond.dx < -300.0) {
            goToLoginPage();
          }
        },
        child: page,
      );
    }
    return page;
  }

  Widget buildBtn() {
    return Positioned(
      right: -3.w,
      bottom: 160.h,
      child: Container(
          height: 68.h,
          width: 93.w,
          clipBehavior: Clip.hardEdge,
          decoration: BoxDecoration(
              color: Colors.transparent,
              border: Border.all(width: 3, color: const Color(0xFFD5CBFF)),
              borderRadius: BorderRadius.only(topLeft: Radius.circular(35.h), bottomLeft: Radius.circular(35.h))),
          child: GestureDetector(
              onTap: goNextOrLogin,
              child: JrBlurContainer(
                padding: EdgeInsets.only(left: 6.w),
                outerRadius: BorderRadius.only(topLeft: Radius.circular(35.h), bottomLeft: Radius.circular(35.h)),
                color: Colors.white.withOpacity(0.3),
                child: Row(
                  children: [
                    Container(
                      height: 56.r,
                      width: 56.r,
                      decoration: BoxDecoration(
                          gradient: const LinearGradient(
                            colors: [
                              Color.fromRGBO(138, 109, 255, 1),
                              Color.fromRGBO(173, 109, 255, 1),
                            ],
                            begin: Alignment(0.17, 0.07),
                            end: Alignment(0.76, 0.94),
                          ),
                          borderRadius: BorderRadius.circular(30.r)),
                      child: Center(
                        child: isLast
                            ? const Text(
                                'GO',
                                style: TextStyle(fontSize: 24, color: Colors.white, fontWeight: FontWeight.w800),
                              )
                            : SvgPicture.asset(
                                'assets/svg/icon_next.svg',
                                height: 27.r,
                              ),
                      ),
                    )
                  ],
                ),
              ))),
    );
  }

  Future<void> goNextOrLogin() async {
    if (isLast) {
      await goToLoginPage();
    } else {
      await goToNextPage();
    }
  }

  Future<void> goToNextPage() async {
    swiperController?.next();
  }

  Future<void> goToLoginPage() async {
    Get.offAll(() => const JrLoginView());
  }
}
